# MIT License
# 
# Copyright (c) 2024 - present @ ebraid
# 
# Email: 1477153217@qq.com
# QQ: 1477153217
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# 

# check os type
ifneq ($(wildcard /etc/os-release),)
    LD_SCRIPT = $(LDS_SOURCE)-linux
	LD_PATCH  = linkpatch-linux.h
else
    LD_SCRIPT = $(LDS_SOURCE)-win
	LD_PATCH  = linkpatch-win.h
endif


TARGET    = x86_64
BUILD_DIR := build
CFLAGS    := $(C_PATH) $(C_DEFINE) $(C_FLAG)
LDFLAGS   := $(LD_FLAG) -T$(LD_SCRIPT).fina -Wl,-Map=$(BUILD_DIR)/$(TARGET).map


.PHONY: all


all: $(BUILD_DIR)/$(TARGET).exe  elf_info


# list of c program objects
OBJECTS = $(addprefix $(BUILD_DIR)/,$(notdir $(C_SOURCE:.c=.o)))
vpath %.c $(sort $(dir $(C_SOURCE)))


$(BUILD_DIR)/%.o: %.c Makefile | $(BUILD_DIR)
	@echo "CC   $<"
	@$(CC) -c $(CFLAGS) $< -o $@


$(BUILD_DIR)/$(TARGET).exe: $(OBJECTS) Makefile
	@echo "LD   $@"
	@$(CC) -E -P -x assembler-with-cpp -include arch/$(CONFIG_ARCH)/$(LD_PATCH) $(LD_SCRIPT) -o $(LD_SCRIPT).fina
	@$(CC) $(OBJECTS) $(LDFLAGS) -o $@
	@$(OD) $(BUILD_DIR)/$(TARGET).exe -xS > $(BUILD_DIR)/$(TARGET).s $@
	@echo ''
	@echo  "Build Successful!"
	@echo ''
	@echo "ELF   $@"
	@$(LM) --rm $(LD_SCRIPT).fina


elf_info: $(BUILD_DIR)/$(TARGET).exe
	@echo "=================================================================="
	@$(SZ) $<
	@echo "=================================================================="


run: $(BUILD_DIR)/$(TARGET).exe
	@echo "start to run $< "
	@./$<
